package com.zenithmind.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zenithmind.user.mapper.UserRoleMapper;
import com.zenithmind.user.pojo.domain.UserRole;
import com.zenithmind.user.service.UserRoleService;
import com.zenithmind.common.annotation.DataCache;
import com.zenithmind.common.annotation.DataCacheEvict;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserRoleServiceImpl extends ServiceImpl<UserRoleMapper, UserRole> implements UserRoleService {

    /**
     * 根据用户ID获取角色关联
     * 
     * @param userId 用户ID
     * @return 用户角色关联
     */
    @DataCache(prefix = "user:role", key = "#userId")
    public UserRole getByUserId(String userId) {
        LambdaQueryWrapper<UserRole> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserRole::getUserId, userId);
        return getOne(wrapper);
    }

    /**
     * 根据角色ID获取用户关联列表
     * 
     * @param roleId 角色ID
     * @return 用户角色关联列表
     */
    @DataCache(prefix = "role:users", key = "#roleId")
    public List<UserRole> getByRoleId(String roleId) {
        LambdaQueryWrapper<UserRole> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserRole::getRoleId, roleId);
        return list(wrapper);
    }

    /**
     * 保存用户角色关联
     * 
     * @param userRole 用户角色关联
     * @return 是否成功
     */
    @DataCacheEvict(prefix = "user:role", allEntries = true)
    public boolean saveUserRole(UserRole userRole) {
        return save(userRole);
    }

    /**
     * 更新用户角色关联
     * 
     * @param userRole 用户角色关联
     * @return 是否成功
     */
    @DataCacheEvict(prefix = "user:role", allEntries = true)
    public boolean updateUserRole(UserRole userRole) {
        return updateById(userRole);
    }

    /**
     * 删除用户角色关联
     * 
     * @param id 关联ID
     * @return 是否成功
     */
    @DataCacheEvict(prefix = "user:role", allEntries = true)
    public boolean removeUserRole(String id) {
        return removeById(id);
    }

    /**
     * 根据用户ID删除角色关联
     * 
     * @param userId 用户ID
     * @return 是否成功
     */
    @DataCacheEvict(prefix = "user:role", allEntries = true)
    public boolean removeByUserId(String userId) {
        LambdaQueryWrapper<UserRole> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserRole::getUserId, userId);
        return remove(wrapper);
    }

    /**
     * 根据角色ID删除用户关联
     * 
     * @param roleId 角色ID
     * @return 是否成功
     */
    @DataCacheEvict(prefix = "user:role", allEntries = true)
    public boolean removeByRoleId(String roleId) {
        LambdaQueryWrapper<UserRole> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserRole::getRoleId, roleId);
        return remove(wrapper);
    }
}
